//
//  MFWHttpTask.m
//  MFWSdk
//
//  Created by Song Xiaofeng on 13-7-24.
//  Copyright (c) 2013年 Mafengwo Inc. All rights reserved.
//

#import "MFWHttpTask.h"
#import "NSMutableSet+WeakReference.h"

@implementation MFWHttpTask

- (id)init
{
    self = [super init];
    if (self)
    {
        _argsDic = [NSMutableDictionary dictionary];
        _senders = [NSMutableSet set];
    }
    return self;
}
- (BOOL)addToEngine;
{
    return [[MFWHttpEngine sharedInstance] addTask:self];
}

+ (MFWHttpTask*)task;
{
    MFWHttpTask *task = [[MFWHttpTask alloc] init];
    return task;
}

+ (MFWHttpTask*)taskWithSender:(id)sender forDataIdentifier:(MFWDataIdentifier*)dataIdentifier;
{
    return [self taskWithSender:sender forDataIdentifier:dataIdentifier requestType:kMFWDataRequest_Refresh];
}

+ (MFWHttpTask*)taskWithSender:(id)sender forDataIdentifier:(MFWDataIdentifier *)dataIdentifier requestType:(MFWDataRequestType)requestType;
{
    MFWHttpTask *task = [[MFWHttpTask alloc] init];
    
    [task.senders addWeakObject:sender];
    task.dataIdentifier = dataIdentifier;
    task.dataRequestType = requestType;
    
    return task;
}

- (NSString*)description
{
    NSMutableString *description = [[NSMutableString alloc] init];
    
    [description appendFormat:@"%@ for %@ \n args:%@", NSStringFromClass([self class]), _dataIdentifier, _argsDic];
    return description;
}

- (void)cancel;
{
    [[MFWHttpEngine sharedInstance] cancelTask:self];
}

- (BOOL)isEqual:(id)object
{
    if (object && [object isKindOfClass:[MFWHttpTask class]])
    {
        MFWHttpTask *task = (MFWHttpTask*)object;
        return [self.dataIdentifier isEqual:task.dataIdentifier]
                && self.dataRequestType == task.dataRequestType
                && [self.argsDic isEqualToDictionary:task.argsDic];
    }
    return NO;
}
@end


